// 神秘学香薰蜡烛制作助手 - 主应用逻辑

// DOM 元素引用
const elements = {
    // 主要区域
    welcomeSection: null,
    creationSection: null,
    inventorySection: null,
    
    // 按钮
    startCreationBtn: null,
    inventoryBtn: null,
    backToHomeBtn: null,
    prevBtn: null,
    nextBtn: null,
    finishBtn: null,
    
    // 步骤内容
    stepContents: [],
    progressSteps: [],
    
    // 输入元素
    waxAmountInput: null,
    sellingPriceInput: null,
    
    // 显示元素
    effectsGrid: null,
    oilsGrid: null,
    waxOptions: null,
    containersGrid: null,
    packagingGrid: null,
    costBreakdown: null,
    totalCostDisplay: null,
    profitMarginDisplay: null,
    inventoryList: null,
    totalProductsDisplay: null,
    totalValueDisplay: null,
    
    // 模态框
    modal: null,
    modalTitle: null,
    modalBody: null,
    modalClose: null
};

// 应用初始化
class CandleApp {
    constructor() {
        this.inventory = [];
        this.isSupabaseConnected = false;
    }
    
    // 初始化应用
    async init() {
        this.initializeElements();
        this.bindEvents();
        this.initializeSupabase();
        await this.loadInventory();
        this.showWelcomeScreen();
        
        // 预加载数据
        await this.preloadData();
        
        console.log('神秘学香薰蜡烛制作助手已启动');
    }
    
    // 预加载数据
    async preloadData() {
        try {
            // 预加载所有基础数据
            await Promise.all([
                DataManager.getEssentialOils(),
                DataManager.getContainers(),
                DataManager.getPackagingTypes(),
                DataManager.getWaxTypes(),
                DataManager.getEffectCategories()
            ]);
            console.log('预加载数据完成');
        } catch (error) {
            console.warn('预加载数据失败:', error);
        }
    }
    
    // 初始化DOM元素
    initializeElements() {
        // 主要区域
        elements.welcomeSection = document.getElementById('welcomeSection');
        elements.creationSection = document.getElementById('creationSection');
        elements.inventorySection = document.getElementById('inventorySection');
        
        // 按钮
        elements.startCreationBtn = document.getElementById('startCreationBtn');
        elements.inventoryBtn = document.getElementById('inventoryBtn');
        elements.backToHomeBtn = document.getElementById('backToHomeBtn');
        elements.prevBtn = document.getElementById('prevBtn');
        elements.nextBtn = document.getElementById('nextBtn');
        elements.finishBtn = document.getElementById('finishBtn');
        
        // 步骤相关
        elements.stepContents = Array.from(document.querySelectorAll('.step-content'));
        elements.progressSteps = Array.from(document.querySelectorAll('.progress-step'));
        
        // 输入元素
        elements.waxAmountInput = document.getElementById('waxAmount');
        elements.sellingPriceInput = document.getElementById('sellingPrice');
        
        // 网格容器
        elements.effectsGrid = document.getElementById('effectsGrid');
        elements.oilsGrid = document.getElementById('oilsGrid');
        elements.waxOptions = document.getElementById('waxOptions');
        elements.containersGrid = document.getElementById('containersGrid');
        elements.packagingGrid = document.getElementById('packagingGrid');
        
        // 成本显示
        elements.costBreakdown = document.getElementById('costBreakdown');
        elements.totalCostDisplay = document.getElementById('totalCost');
        elements.profitMarginDisplay = document.getElementById('profitMargin');
        
        // 库存相关
        elements.inventoryList = document.getElementById('inventoryList');
        elements.totalProductsDisplay = document.getElementById('totalProducts');
        elements.totalValueDisplay = document.getElementById('totalValue');
        
        // 模态框
        elements.modal = document.getElementById('modal');
        elements.modalTitle = document.getElementById('modalTitle');
        elements.modalBody = document.getElementById('modalBody');
        elements.modalClose = document.getElementById('modalClose');
    }
    
    // 绑定事件
    bindEvents() {
        // 主要导航
        elements.startCreationBtn?.addEventListener('click', () => this.startCreation());
        elements.inventoryBtn?.addEventListener('click', () => this.showInventory());
        elements.backToHomeBtn?.addEventListener('click', () => this.showWelcomeScreen());
        
        // 步骤导航
        elements.prevBtn?.addEventListener('click', () => this.previousStep());
        elements.nextBtn?.addEventListener('click', () => this.nextStep());
        elements.finishBtn?.addEventListener('click', () => this.finishCreation());
        
        // 输入变化
        elements.waxAmountInput?.addEventListener('input', () => this.updateCost());
        elements.sellingPriceInput?.addEventListener('input', () => this.updateProfitMargin());
        
        // 模态框
        elements.modalClose?.addEventListener('click', () => this.closeModal());
        elements.modal?.addEventListener('click', (e) => {
            if (e.target === elements.modal) this.closeModal();
        });
        
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') this.closeModal();
        });
    }
    
    // 初始化Supabase
    initializeSupabase() {
        this.isSupabaseConnected = initializeSupabase();
        if (!this.isSupabaseConnected) {
            showNotification('数据库连接失败，将使用本地存储', 'error');
        }
    }
    
    // 显示欢迎屏幕
    showWelcomeScreen() {
        this.hideAllSections();
        elements.welcomeSection?.classList.remove('hidden');
        AppState.reset();
    }
    
    // 开始制作流程
    async startCreation() {
        this.hideAllSections();
        elements.creationSection?.classList.remove('hidden');
        AppState.reset();
        this.updateStepDisplay();
        await this.renderEffects();
    }
    
    // 显示库存管理
    async showInventory() {
        this.hideAllSections();
        elements.inventorySection?.classList.remove('hidden');
        await this.loadInventory();
        this.renderInventory();
    }
    
    // 隐藏所有区域
    hideAllSections() {
        elements.welcomeSection?.classList.add('hidden');
        elements.creationSection?.classList.add('hidden');
        elements.inventorySection?.classList.add('hidden');
    }
    
    // 上一步
    previousStep() {
        if (AppState.currentStep > 1) {
            AppState.currentStep--;
            this.updateStepDisplay();
        }
    }
    
    // 下一步
    async nextStep() {
        if (this.validateCurrentStep()) {
            if (AppState.currentStep < AppState.maxSteps) {
                AppState.currentStep++;
                this.updateStepDisplay();
                await this.renderCurrentStep();
            }
        }
    }
    
    // 验证当前步骤
    validateCurrentStep() {
        switch (AppState.currentStep) {
            case 1:
                if (!AppState.selectedEffect) {
                    showNotification('请选择一个功效', 'error');
                    return false;
                }
                break;
            case 2:
                if (AppState.selectedOils.length === 0) {
                    showNotification('请至少选择一种精油', 'error');
                    return false;
                }
                break;
            case 3:
                if (!AppState.selectedWax) {
                    showNotification('请选择蜡材类型', 'error');
                    return false;
                }
                break;
            case 4:
                if (!AppState.selectedContainer) {
                    showNotification('请选择容器', 'error');
                    return false;
                }
                break;
            case 5:
                if (!AppState.selectedPackaging) {
                    showNotification('请选择包装', 'error');
                    return false;
                }
                break;
        }
        return true;
    }
    
    // 更新步骤显示
    updateStepDisplay() {
        // 更新进度条
        elements.progressSteps.forEach((step, index) => {
            if (index + 1 <= AppState.currentStep) {
                step.classList.add('active');
            } else {
                step.classList.remove('active');
            }
        });
        
        // 更新步骤内容
        elements.stepContents.forEach((content, index) => {
            if (index + 1 === AppState.currentStep) {
                content.classList.add('active');
            } else {
                content.classList.remove('active');
            }
        });
        
        // 更新按钮状态
        if (elements.prevBtn) {
            elements.prevBtn.disabled = AppState.currentStep === 1;
        }
        
        if (AppState.currentStep === AppState.maxSteps) {
            elements.nextBtn?.classList.add('hidden');
            elements.finishBtn?.classList.remove('hidden');
        } else {
            elements.nextBtn?.classList.remove('hidden');
            elements.finishBtn?.classList.add('hidden');
        }
    }
    
    // 渲染当前步骤
    async renderCurrentStep() {
        switch (AppState.currentStep) {
            case 2:
                await this.renderOils();
                break;
            case 3:
                await this.renderWaxOptions();
                break;
            case 4:
                await this.renderContainers();
                break;
            case 5:
                await this.renderPackaging();
                break;
            case 6:
                this.renderCostSummary();
                break;
        }
    }
    
    // 渲染功效选择
    async renderEffects() {
        if (!elements.effectsGrid) return;
        
        try {
            const effects = await DataManager.getEffectCategories();
            elements.effectsGrid.innerHTML = effects.map(effect => `
                <div class="effect-card" data-effect-id="${effect.id}">
                    <div class="card-icon">
                        <i class="${effect.icon}"></i>
                    </div>
                    <div class="card-title">${effect.name}</div>
                    <div class="card-description">${effect.description}</div>
                </div>
            `).join('');
            
            // 绑定点击事件
            elements.effectsGrid.querySelectorAll('.effect-card').forEach(card => {
                card.addEventListener('click', () => {
                    const effectId = card.dataset.effectId;
                    this.selectEffect(effectId);
                    
                    // 更新UI
                    elements.effectsGrid.querySelectorAll('.effect-card').forEach(c => c.classList.remove('selected'));
                    card.classList.add('selected');
                });
            });
        } catch (error) {
            console.error('渲染功效失败:', error);
            elements.effectsGrid.innerHTML = '<p class="error-message">加载功效数据失败，请稍后重试</p>';
        }
    }
    
    // 选择功效
    async selectEffect(effectId) {
        try {
            const effects = await DataManager.getEffectCategories();
            AppState.selectedEffect = effects.find(e => e.id === effectId);
            console.log('选择功效:', AppState.selectedEffect);
        } catch (error) {
            console.error('选择功效失败:', error);
        }
    }
    
    // 渲染精油选择
    async renderOils() {
        if (!elements.oilsGrid) return;
        
        try {
            const allOils = await DataManager.getEssentialOils();
            
            // 获取推荐精油
            const recommendedOils = RecommendationEngine.recommendOilsByEffect(AppState.selectedEffect?.id, allOils);
            
            // 优先显示推荐精油
            const sortedOils = [...recommendedOils, ...allOils.filter(oil => 
                !recommendedOils.find(rec => rec.id === oil.id)
            )];
            
            elements.oilsGrid.innerHTML = sortedOils.map(oil => {
                const isRecommended = recommendedOils.find(rec => rec.id === oil.id);
                return `
                    <div class="oil-card ${isRecommended ? 'recommended' : ''}" data-oil-id="${oil.id}">
                        ${isRecommended ? '<div class="recommended-badge">推荐</div>' : ''}
                        <div class="card-icon">
                            <i class="${oil.icon}"></i>
                        </div>
                        <div class="card-title">${oil.name}</div>
                        <div class="card-description">${oil.effects.join('、')}</div>
                        <div class="card-price">¥${oil.price_per_10ml}/10ml</div>
                    </div>
                `;
            }).join('');
            
            // 绑定点击事件
            elements.oilsGrid.querySelectorAll('.oil-card').forEach(card => {
                card.addEventListener('click', () => {
                    const oilId = card.dataset.oilId;
                    this.toggleOilSelection(oilId, card);
                });
            });
        } catch (error) {
            console.error('渲染精油失败:', error);
            elements.oilsGrid.innerHTML = '<p class="error-message">加载精油数据失败，请稍后重试</p>';
        }
    }
    
    // 切换精油选择
    async toggleOilSelection(oilId, cardElement) {
        try {
            const allOils = await DataManager.getEssentialOils();
            const oil = allOils.find(o => o.id === oilId);
            if (!oil) return;
            
            const index = AppState.selectedOils.findIndex(o => o.id === oilId);
            
            if (index > -1) {
                // 取消选择
                AppState.selectedOils.splice(index, 1);
                cardElement.classList.remove('selected');
            } else {
                // 限制最多选择3种精油
                if (AppState.selectedOils.length >= 3) {
                    showNotification('最多只能选择3种精油', 'error');
                    return;
                }
                
                // 添加选择
                AppState.selectedOils.push(oil);
                cardElement.classList.add('selected');
            }
            
            console.log('已选择精油:', AppState.selectedOils);
        } catch (error) {
            console.error('切换精油选择失败:', error);
        }
    }
    
    // 渲染蜡材选择
    async renderWaxOptions() {
        if (!elements.waxOptions) return;
        
        try {
            const waxTypes = await DataManager.getWaxTypes();
            elements.waxOptions.innerHTML = waxTypes.map(wax => `
                <div class="wax-card" data-wax-id="${wax.id}">
                    <div class="card-icon">
                        <i class="${wax.icon}"></i>
                    </div>
                    <div class="card-title">${wax.name}</div>
                    <div class="card-description">${wax.properties.join('、')}</div>
                    <div class="card-price">¥${wax.price_per_kg}/kg</div>
                    <div class="burn-time">燃烧时间: ${wax.burn_time_per_100g}</div>
                </div>
            `).join('');
            
            // 绑定点击事件
            elements.waxOptions.querySelectorAll('.wax-card').forEach(card => {
                card.addEventListener('click', () => {
                    const waxId = card.dataset.waxId;
                    this.selectWax(waxId);
                    
                    // 更新UI
                    elements.waxOptions.querySelectorAll('.wax-card').forEach(c => c.classList.remove('selected'));
                    card.classList.add('selected');
                });
            });
            
            // 设置默认蜡量
            if (elements.waxAmountInput) {
                elements.waxAmountInput.value = AppState.waxAmount;
            }
        } catch (error) {
            console.error('渲染蜡材失败:', error);
            elements.waxOptions.innerHTML = '<p class="error-message">加载蜡材数据失败，请稍后重试</p>';
        }
    }
    
    // 选择蜡材
    async selectWax(waxId) {
        try {
            const waxTypes = await DataManager.getWaxTypes();
            AppState.selectedWax = waxTypes.find(w => w.id === waxId);
            AppState.waxAmount = parseInt(elements.waxAmountInput?.value || 200);
            console.log('选择蜡材:', AppState.selectedWax);
        } catch (error) {
            console.error('选择蜡材失败:', error);
        }
    }
    
    // 渲染容器选择
    async renderContainers() {
        if (!elements.containersGrid) return;
        
        try {
            const containers = await DataManager.getContainers();
            
            // 获取推荐容器
            const recommendedContainers = RecommendationEngine.recommendContainerByOils(AppState.selectedOils, containers);
            
            elements.containersGrid.innerHTML = containers.map(container => {
                const isRecommended = recommendedContainers.find(rec => rec.id === container.id);
                return `
                    <div class="container-card ${isRecommended ? 'recommended' : ''}" data-container-id="${container.id}">
                        ${isRecommended ? '<div class="recommended-badge">推荐</div>' : ''}
                        <div class="card-icon" style="color: ${this.getColorCode(container.color)}">
                            <i class="${container.icon}"></i>
                        </div>
                        <div class="card-title">${container.name}</div>
                        <div class="card-description">${container.symbolism.join('、')}</div>
                        <div class="card-price">¥${container.price}</div>
                        <div class="capacity">${container.capacity}</div>
                    </div>
                `;
            }).join('');
            
            // 绑定点击事件
            elements.containersGrid.querySelectorAll('.container-card').forEach(card => {
                card.addEventListener('click', () => {
                    const containerId = card.dataset.containerId;
                    this.selectContainer(containerId);
                    
                    // 更新UI
                    elements.containersGrid.querySelectorAll('.container-card').forEach(c => c.classList.remove('selected'));
                    card.classList.add('selected');
                });
            });
        } catch (error) {
            console.error('渲染容器失败:', error);
            elements.containersGrid.innerHTML = '<p class="error-message">加载容器数据失败，请稍后重试</p>';
        }
    }
    
    // 选择容器
    async selectContainer(containerId) {
        try {
            const containers = await DataManager.getContainers();
            AppState.selectedContainer = containers.find(c => c.id === containerId);
            console.log('选择容器:', AppState.selectedContainer);
        } catch (error) {
            console.error('选择容器失败:', error);
        }
    }
    
    // 渲染包装选择
    async renderPackaging() {
        if (!elements.packagingGrid) return;
        
        try {
            const packaging = await DataManager.getPackagingTypes();
            elements.packagingGrid.innerHTML = packaging.map(pkg => `
                <div class="package-card" data-package-id="${pkg.id}">
                    <div class="card-icon">
                        <i class="${pkg.icon}"></i>
                    </div>
                    <div class="card-title">${pkg.name}</div>
                    <div class="card-description">${pkg.description}</div>
                    <div class="card-price">¥${pkg.price}</div>
                </div>
            `).join('');
            
            // 绑定点击事件
            elements.packagingGrid.querySelectorAll('.package-card').forEach(card => {
                card.addEventListener('click', () => {
                    const packageId = card.dataset.packageId;
                    this.selectPackaging(packageId);
                    
                    // 更新UI
                    elements.packagingGrid.querySelectorAll('.package-card').forEach(c => c.classList.remove('selected'));
                    card.classList.add('selected');
                });
            });
        } catch (error) {
            console.error('渲染包装失败:', error);
            elements.packagingGrid.innerHTML = '<p class="error-message">加载包装数据失败，请稍后重试</p>';
        }
    }
    
    // 选择包装
    async selectPackaging(packageId) {
        try {
            const packaging = await DataManager.getPackagingTypes();
            AppState.selectedPackaging = packaging.find(p => p.id === packageId);
            console.log('选择包装:', AppState.selectedPackaging);
        } catch (error) {
            console.error('选择包装失败:', error);
        }
    }
    
    // 渲染成本汇总
    renderCostSummary() {
        this.updateCost();
        this.updateSuggestedPrices();
    }
    
    // 更新成本计算
    updateCost() {
        AppState.waxAmount = parseInt(elements.waxAmountInput?.value || 200);
        const cost = AppState.calculateCost();
        
        // 更新成本明细
        if (elements.costBreakdown) {
            let breakdown = '';
            
            // 蜡成本
            if (AppState.selectedWax) {
                const waxCost = (AppState.waxAmount / 1000) * AppState.selectedWax.price_per_kg;
                breakdown += `
                    <div class="cost-item">
                        <span>${AppState.selectedWax.name} (${AppState.waxAmount}g)</span>
                        <span>¥${waxCost.toFixed(2)}</span>
                    </div>
                `;
            }
            
            // 精油成本
            AppState.selectedOils.forEach(oil => {
                const oilAmount = (AppState.waxAmount * AppState.oilConcentration / 100) / AppState.selectedOils.length;
                const oilCost = (oilAmount / 10) * oil.price_per_10ml;
                breakdown += `
                    <div class="cost-item">
                        <span>${oil.name} (${oilAmount.toFixed(1)}ml)</span>
                        <span>¥${oilCost.toFixed(2)}</span>
                    </div>
                `;
            });
            
            // 容器成本
            if (AppState.selectedContainer) {
                breakdown += `
                    <div class="cost-item">
                        <span>${AppState.selectedContainer.name}</span>
                        <span>¥${AppState.selectedContainer.price}</span>
                    </div>
                `;
            }
            
            // 包装成本
            if (AppState.selectedPackaging) {
                breakdown += `
                    <div class="cost-item">
                        <span>${AppState.selectedPackaging.name}</span>
                        <span>¥${AppState.selectedPackaging.price}</span>
                    </div>
                `;
            }
            
            breakdown += `
                <div class="cost-item">
                    <span><strong>总成本</strong></span>
                    <span><strong>¥${cost.toFixed(2)}</strong></span>
                </div>
            `;
            
            elements.costBreakdown.innerHTML = breakdown;
        }
        
        // 更新总成本显示
        if (elements.totalCostDisplay) {
            elements.totalCostDisplay.textContent = formatPrice(cost);
        }
        
        this.updateProfitMargin();
    }
    
    // 更新利润率
    updateProfitMargin() {
        AppState.sellingPrice = parseFloat(elements.sellingPriceInput?.value || 0);
        AppState.updateProfitMargin();
        
        if (elements.profitMarginDisplay) {
            elements.profitMarginDisplay.textContent = `${AppState.profitMargin}%`;
            
            // 根据利润率设置颜色
            const margin = parseFloat(AppState.profitMargin);
            if (margin < 20) {
                elements.profitMarginDisplay.style.color = '#f56565';
            } else if (margin < 50) {
                elements.profitMarginDisplay.style.color = '#ed8936';
            } else {
                elements.profitMarginDisplay.style.color = '#48bb78';
            }
        }
    }
    
    // 更新建议价格
    updateSuggestedPrices() {
        const suggestions = RecommendationEngine.getSuggestedPrice(AppState.totalCost);
        
        // 设置默认售价为建议价格
        if (elements.sellingPriceInput && !elements.sellingPriceInput.value) {
            elements.sellingPriceInput.value = suggestions.suggested;
            AppState.sellingPrice = suggestions.suggested;
            this.updateProfitMargin();
        }
    }
    
    // 完成制作
    async finishCreation() {
        if (!validateProductData(AppState)) {
            showNotification('请完成所有必要的选择', 'error');
            return;
        }
        
        try {
            const productData = AppState.getProductData();
            
            // 保存到数据库或本地存储
            if (this.isSupabaseConnected) {
                await DatabaseManager.saveProduct(productData);
            } else {
                this.saveToLocalStorage(productData);
            }
            
            // 添加到本地库存
            this.inventory.push(productData);
            
            showNotification('香薰蜡烛制作完成！', 'success');
            
            // 显示完成模态框
            this.showCompletionModal(productData);
            
        } catch (error) {
            console.error('保存产品失败:', error);
            showNotification('保存失败，请重试', 'error');
        }
    }
    
    // 保存到本地存储
    saveToLocalStorage(productData) {
        const stored = JSON.parse(localStorage.getItem('candle_inventory') || '[]');
        stored.push(productData);
        localStorage.setItem('candle_inventory', JSON.stringify(stored));
    }
    
    // 从本地存储加载
    loadFromLocalStorage() {
        return JSON.parse(localStorage.getItem('candle_inventory') || '[]');
    }
    
    // 加载库存
    async loadInventory() {
        try {
            if (this.isSupabaseConnected) {
                this.inventory = await DatabaseManager.getProducts();
            } else {
                this.inventory = this.loadFromLocalStorage();
            }
        } catch (error) {
            console.error('加载库存失败:', error);
            this.inventory = this.loadFromLocalStorage();
        }
    }
    
    // 渲染库存
    renderInventory() {
        // 更新统计
        if (elements.totalProductsDisplay) {
            elements.totalProductsDisplay.textContent = this.inventory.length;
        }
        
        if (elements.totalValueDisplay) {
            const totalValue = this.inventory.reduce((sum, item) => sum + (item.sellingPrice || 0), 0);
            elements.totalValueDisplay.textContent = formatPrice(totalValue);
        }
        
        // 渲染库存列表
        if (elements.inventoryList) {
            if (this.inventory.length === 0) {
                elements.inventoryList.innerHTML = `
                    <div class="empty-inventory">
                        <i class="fas fa-box-open"></i>
                        <h3>库存为空</h3>
                        <p>开始制作您的第一个香薰蜡烛吧！</p>
                    </div>
                `;
            } else {
                elements.inventoryList.innerHTML = this.inventory.map(item => `
                    <div class="inventory-item">
                        <div class="item-info">
                            <h4>${item.name}</h4>
                            <p>${item.effect?.name || '未知功效'}</p>
                            <div class="item-details">
                                <span>成本: ${formatPrice(item.cost)}</span>
                                <span>售价: ${formatPrice(item.sellingPrice)}</span>
                                <span>利润率: ${item.profitMargin}%</span>
                            </div>
                        </div>
                        <div class="item-actions">
                            <button class="secondary-btn" onclick="app.editProduct('${item.id}')">
                                <i class="fas fa-edit"></i>
                                编辑
                            </button>
                            <button class="secondary-btn" onclick="app.deleteProduct('${item.id}')">
                                <i class="fas fa-trash"></i>
                                删除
                            </button>
                        </div>
                    </div>
                `).join('');
            }
        }
    }
    
    // 编辑产品
    editProduct(productId) {
        const product = this.inventory.find(p => p.id === productId);
        if (!product) return;
        
        // 显示编辑模态框
        this.showEditModal(product);
    }
    
    // 删除产品
    async deleteProduct(productId) {
        if (!confirm('确定要删除这个产品吗？')) return;
        
        try {
            if (this.isSupabaseConnected) {
                await DatabaseManager.deleteProduct(productId);
            }
            
            // 从本地库存移除
            this.inventory = this.inventory.filter(p => p.id !== productId);
            
            // 更新本地存储
            if (!this.isSupabaseConnected) {
                localStorage.setItem('candle_inventory', JSON.stringify(this.inventory));
            }
            
            this.renderInventory();
            showNotification('产品已删除', 'success');
            
        } catch (error) {
            console.error('删除产品失败:', error);
            showNotification('删除失败，请重试', 'error');
        }
    }
    
    // 显示完成模态框
    showCompletionModal(productData) {
        if (!elements.modal) return;
        
        elements.modalTitle.textContent = '制作完成！';
        elements.modalBody.innerHTML = `
            <div class="completion-content">
                <div class="success-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <h3>${productData.name}</h3>
                <div class="product-summary">
                    <div class="summary-item">
                        <span>功效:</span>
                        <span>${productData.effect.name}</span>
                    </div>
                    <div class="summary-item">
                        <span>精油:</span>
                        <span>${productData.oils.map(oil => oil.name).join('、')}</span>
                    </div>
                    <div class="summary-item">
                        <span>成本:</span>
                        <span>${formatPrice(productData.cost)}</span>
                    </div>
                    <div class="summary-item">
                        <span>售价:</span>
                        <span>${formatPrice(productData.sellingPrice)}</span>
                    </div>
                    <div class="summary-item">
                        <span>利润率:</span>
                        <span>${productData.profitMargin}%</span>
                    </div>
                </div>
                <div class="modal-actions">
                    <button class="primary-btn" onclick="app.startCreation()">
                        <i class="fas fa-plus"></i>
                        制作新蜡烛
                    </button>
                    <button class="secondary-btn" onclick="app.showInventory()">
                        <i class="fas fa-boxes"></i>
                        查看库存
                    </button>
                </div>
            </div>
        `;
        
        this.showModal();
    }
    
    // 显示编辑模态框
    showEditModal(product) {
        if (!elements.modal) return;
        
        elements.modalTitle.textContent = '编辑产品';
        elements.modalBody.innerHTML = `
            <div class="edit-form">
                <div class="form-group">
                    <label for="editSellingPrice">售价:</label>
                    <input type="number" id="editSellingPrice" value="${product.sellingPrice}" step="0.01" min="0">
                </div>
                <div class="form-group">
                    <label for="editStatus">状态:</label>
                    <select id="editStatus">
                        <option value="in_stock" ${product.status === 'in_stock' ? 'selected' : ''}>库存中</option>
                        <option value="sold" ${product.status === 'sold' ? 'selected' : ''}>已售出</option>
                        <option value="reserved" ${product.status === 'reserved' ? 'selected' : ''}>预定</option>
                    </select>
                </div>
                <div class="modal-actions">
                    <button class="primary-btn" onclick="app.saveProductEdit('${product.id}')">
                        <i class="fas fa-save"></i>
                        保存
                    </button>
                    <button class="secondary-btn" onclick="app.closeModal()">
                        取消
                    </button>
                </div>
            </div>
        `;
        
        this.showModal();
    }
    
    // 保存产品编辑
    async saveProductEdit(productId) {
        const sellingPrice = parseFloat(document.getElementById('editSellingPrice')?.value || 0);
        const status = document.getElementById('editStatus')?.value || 'in_stock';
        
        try {
            const updates = {
                sellingPrice,
                status,
                profitMargin: calculateProfitMargin(
                    this.inventory.find(p => p.id === productId)?.cost || 0,
                    sellingPrice
                )
            };
            
            if (this.isSupabaseConnected) {
                await DatabaseManager.updateProduct(productId, updates);
            }
            
            // 更新本地库存
            const productIndex = this.inventory.findIndex(p => p.id === productId);
            if (productIndex > -1) {
                Object.assign(this.inventory[productIndex], updates);
            }
            
            // 更新本地存储
            if (!this.isSupabaseConnected) {
                localStorage.setItem('candle_inventory', JSON.stringify(this.inventory));
            }
            
            this.closeModal();
            this.renderInventory();
            showNotification('产品已更新', 'success');
            
        } catch (error) {
            console.error('更新产品失败:', error);
            showNotification('更新失败，请重试', 'error');
        }
    }
    
    // 显示模态框
    showModal() {
        elements.modal?.classList.remove('hidden');
    }
    
    // 关闭模态框
    closeModal() {
        elements.modal?.classList.add('hidden');
    }
    
    // 获取颜色代码
    getColorCode(colorName) {
        const colorMap = {
            '白色': '#ffffff',
            '紫色': '#9f7aea',
            '绿色': '#48bb78',
            '蓝色': '#4299e1',
            '红色': '#f56565',
            '黑色': '#2d3748',
            '黄色': '#ecc94b'
        };
        return colorMap[colorName] || '#718096';
    }
}

// 创建应用实例
const app = new CandleApp();

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    app.init();
});

// 导出应用实例供全局使用
window.app = app;